package com.gmail.blackdog1987.carcare.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.gmail.blackdog1987.carcare.entity.TUser;
import com.gmail.blackdog1987.carcare.util.PackageUtil;

/**
 * 
 * @author 董国超
 *
 */
public class DbOpenHelper extends SQLiteOpenHelper {

	/** 数据库文件名。 */
	private static final String DB_NAME = "carcare.db";

	private List<BaseModel> mModelList;

	/**
	 * 创建SQLiteOpenHelper。
	 * @param context 
	 */
	public DbOpenHelper(Context context) {
		// --------------------------------------------------
		// 以程序版本号作为数据库版本
		// 如：102030411解释为 1.02.03.0411
		super(context, DB_NAME, null, PackageUtil.getVersionCode(context));

		// --------------------------------------------------
		// 表和视图的ModelList
		mModelList = new ArrayList<BaseModel>();
		mModelList.add(new TUser());
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		List<String> lst = new ArrayList<String>();
		for (BaseModel model : mModelList) {
			lst.addAll(model.getCreateSqlList());
		}
		executeTransaction(db, lst);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		List<String> lst = new ArrayList<String>();
		for (BaseModel model : mModelList) {
			lst.addAll(model.getUpgradeSqlList(oldVersion));
		}
		executeTransaction(db, lst);
	}

	/**
	 * 执行数据库事务。
	 * 
	 * @param db 系统数据库助手。
	 * @param lst SQL语句列表。
	 */
	private void executeTransaction(SQLiteDatabase db, List<String> lst) {
		if (lst.size() > 0) {
			db.beginTransaction();
			try {
				for (String sql : lst) {
					db.execSQL(sql);
				}
				db.setTransactionSuccessful();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				db.endTransaction();
			}
		}
	}
}
